//
// Created by xqyr on 2025/3/30.
//

#include "fservice.h"
#include "log/log.h"
FService::FService(const char *name, CBaseWorker *worker)
: CBaseServer(name, worker) {

}

void FService::onOnline(FdbSessionId_t sid, bool is_first) {
    FDB_LOG_D("onOnline sid=%d, is_first=%d\n", sid, is_first);
}

void FService::onOffline(FdbSessionId_t sid, bool is_last) {
    FDB_LOG_D("onOffline sid=%d, is_last=%d\n", sid, is_last);
}

void FService::onBroadcast(CBaseJob::Ptr &msg_ref) {
    FDB_LOG_D("onBroadcast %xd\n",msg_ref.get());
}

void FService::onInvoke(CBaseJob::Ptr &msg_ref) {
    FDB_LOG_D("onInvoke %xd \n",msg_ref.get());
}

void FService::onSubscribe(CBaseJob::Ptr &msg_ref){
   // FDB_LOG_D("onSubscribe\n");
    auto msg = castToMessage<CFdbMessage *>(msg_ref);
    const CFdbMsgSubscribeItem *sub_item;
    FDB_BEGIN_FOREACH_SIGNAL(msg, sub_item)
     {
         FDB_LOG_D("onSubscribe sub_item code=%xd,filter=%s\n",sub_item->msg_code(),sub_item->filter().c_str());
//         CFdbProtoMsgBuilder builder();
         msg->broadcast(sub_item->msg_code());
     }
    FDB_END_FOREACH_SIGNAL()
}
const char* NAME ="TEST";
#define FDB_CONTEXT CFdbContext::getInstance()
static CBaseWorker main_worker;
void * FService::startServer(void *arg) {
    /* start fdbus context thread */
    FDB_CONTEXT->start();
    CBaseWorker *worker_ptr = &main_worker;
    /* start worker thread */
    worker_ptr->start();

    std::string server_name = NAME;
    std::string url(FDB_URL_SVC);
    url += server_name;
    server_name += "_server";
    auto server = new FService(server_name.c_str(), worker_ptr);
    LOG_INFO("server_name = %s, url = %s, bind to %d\n", server_name.c_str(), url.c_str(), server->bind(url.c_str()));

    /* convert main thread into worker */
    CBaseWorker background_worker;
    LOG_INFO("FService::startServer end = %d\n",  background_worker.start(FDB_WORKER_EXE_IN_PLACE));
}
